const https = require('https');
const express = require('express')
const app = express();
const ejs = require('ejs');
const path = require('path')
const bodyParser = require('body-parser');
const fs = require('fs');
// var compression = require('compression')

// variable
const socketio = require('./socket.io-server');

//同步读取密钥和签名证书(证书需要后后台一致)
const options = {
    key: fs.readFileSync(path.resolve(__dirname, '../ssl/club.rsa')),
    cert: fs.readFileSync(path.resolve(__dirname, '../ssl/club.crt'))
}
const httpsServer = https.createServer(options, app);

// 开启gzip压缩
// app.use(compression({filter: (req, res) => {
//     if (req.headers['x-no-compression']) {
//         // 这里就过滤掉了请求头包含'x-no-compression'
//         return false
//       }
    
//       return compression.filter(req, res)
// }}))

// json
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

app.all('*', function (req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Headers', 'Content-Type'); // 不要通配符(*)有些浏览器有bug
    res.header('Access-Control-Allow-Methods', '*');
    res.header('Content-Type', 'application/json;charset=utf-8');
    next();
});
// ejs
app.use(express.static(path.join(__dirname, '../static'))); // 设置静态资源目录

app.engine('html', ejs.__express);
app.set('view engine', 'html'); // 设置模板引擎
app.set('views', path.join(__dirname, '../views')); // 设置模板的目录

app.use((req, res, next) => {
    console.log(`${(new Date()).toLocaleString()} --- 连接中,path:${req.url};`)
    next();
})



app.get('/', (req, res) => {
    res.setHeader('content-type', 'text/html');
    // res.sendFile(path.resolve(__dirname, '../views/index.html'))
    res.render('index.html');
    // res.send(`welcome to socketio+webrtc(nodejs)!`);
})

// 视频分片 headers:range (远程文件分片需要服务端支持)
app.get('/video', (req, res) => {
    let size = 0;
    let fpath = path.resolve(__dirname, '../static/7d515b22c4958598c0fbd1e6290a5ca5.mp4');
    fs.stat(fpath, (error, stats) => {
        if (error) {
            console.error("file size error");
        } else {
            //文件大小
            size = stats.size;

            var rangeQuery = req.headers["range"];
            if (!!rangeQuery) {
                //startIndex 与 endIndex 是索引值,是0开始的,注意在与 Length 比较的时候 Length 要 -1
                var startIndex = 0;
                //视频每节长度为2MB
                var length = 2 * 1024 * 1024;
                var range = rangeQuery.split('=')[1].split('-');
                startIndex = parseInt(range[0]);
                var endIndex = startIndex + length - 1;

                //是否指定了索引终结点
                if (!!range[1]) {
                    endIndex = parseInt(range[1]);
                }
                if (endIndex <= startIndex) {
                    endIndex = startIndex + length - 1;
                }
                if (endIndex > size - 1) {
                    endIndex = size - 1;
                }
                var buf = Buffer.alloc(endIndex - startIndex + 1);
                fs.open(fpath, 'r', (err, fd) => {
                    if (err) {
                        console.error(err);
                        return;
                    }

                    fs.read(fd, buf, 0, buf.length, startIndex, (err, bytesRead, buffer) => {
                        if (err) {
                            console.log(err);
                            return;
                        }
                        res.writeHead(206, { 'Content-Type': 'video/mp4', 'Accept-Ranges': 'bytes', 'Content-Range': `bytes ${startIndex}-${endIndex}/${size}` });

                        const bufferStream = new require('stream').PassThrough();
                        bufferStream.end(buf).pipe(res);

                        bufferStream.on('end', function () {
                            res.end(bufferStream, 'binary');
                        });
                    })
                })

            } else {
                res.writeHead(200, { 'Content-Type': 'video/mp4' });
                var stream = fs.createReadStream(fpath);
                //将文件流用回复管道推出去
                stream.pipe(res);
                stream.on('close', () => {
                    res.end();
                })
            }

        }
    })

})

app.post('/search', (req, res) => {
    let dataJ = req.body;
})


httpsServer.listen(8088);
console.log(`https服务启动成功：https://localhost:8088`);

// 建立socket服务
socketio.initSocketIo(httpsServer);

module.exports = {
    app: app,
    httpsServer: httpsServer,
}
